///////////////////////////////////////////////////////////////////////////////
// File:        TcpConnection.hpp
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#ifndef MONKEY_COMMON_TCPCONNECTION_HPP_
#define MONKEY_COMMON_TCPCONNECTION_HPP_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <pio/server.h>
#include "common/TcpConnectionInputStream.hpp"
#include "common/TcpConnectionOutputStream.hpp"

namespace monkey
{
    namespace common
    {
        class TcpServer;
        class TcpConnectionInputStream;
        class TcpConnectionOutputStream;

        class TcpConnection
        {
        private:
            friend class TcpServer;
            friend class TcpConnectionInputStream;
            friend class TcpConnectionOutputStream;

        public:
            TcpConnection(void);
            ~TcpConnection(void);

        public:
            int GetID(void);
            void Close(void);

            bool ReadImmediately(void);
            bool NotifyWrite(void);

            unsigned int Read(char* buf, unsigned int length);
            unsigned int Peek(char* buf, unsigned int length);
            unsigned int Skip(unsigned int length);
            int Write(const char* buf, unsigned int length);

            bool WritePending(void) const;

        protected:
            virtual bool OnRead(void);
            virtual bool OnWrite(void);
            virtual void OnClose(void);

        private:
            static void _OnRead(struct pio_connection* conn, void* arg);
            static void _OnWrite(struct pio_connection* conn, void* arg);
            static void _OnClose(struct pio_connection* conn, void* arg);

        private:
            void _InitConnection(struct pio_connection* conn, TcpServer* serv);

        private:
            struct pio_connection* conn_;
            TcpServer* serv_;

            bool write_pending_;
            TcpConnectionInputStream is_;
        };
    }
}

#endif /* MONKEY_COMMON_TCPCONNECTION_HPP_ */
